package cn.s1995.sloth.bms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.s1995.sloth.bizs.entity.ApiLog;
import cn.s1995.sloth.bizs.service.ApiLogService;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.excel.annotation.ResponseExcel;
import cn.s1995.sloth.common.log.annotation.SysLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * API日志
 *
 * @author Lex
 * @date 2024-05-18 07:02:13
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/apiLog")
@Tag(description = "ApiLog", name = "API日志管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ApiLogController {

    private final ApiLogService apiLogService;

    /**
     * 获取分页
     * @param page 分页对象
     * @param req API日志
     * @return
     */
	@ApiOperationSupport(order = 1)
    @Operation(summary = "获取分页", description = "获取分页")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('bizs_ApiLog_view')")
    public R getPage(@ParameterObject Page page, @ParameterObject ApiLog req) {
        return R.ok(apiLogService.page(page, buildQueryWrapper(req)));
    }

    /**
     * 获取列表
     * @param req API日志
     * @return
     */
	@ApiOperationSupport(order = 1)
    @Operation(summary = "获取列表", description = "获取列表")
    @GetMapping("/list")
    @PreAuthorize("@pms.hasPermission('bizs_ApiLog_view')")
    public R getList(@ParameterObject ApiLog req) {
        return R.ok(apiLogService.list(buildQueryWrapper(req)));
    }

    /**
     * 获取对象
     * @param id id
     * @return R
     */
	@ApiOperationSupport(order = 1)
    @Operation(summary = "获取对象", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('bizs_ApiLog_view')")
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(apiLogService.getById(id));
    }

    /**
     * 新增API日志
     * @param req API日志
     * @return R
     */
	@ApiOperationSupport(order = 10)
    @Operation(summary = "新增API日志", description = "新增API日志")
    @SysLog("新增API日志")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('bizs_ApiLog_add')")
    public R save(@RequestBody ApiLog req) {
        return R.ok(apiLogService.save(req));
    }

    /**
     * 修改API日志
     * @param req API日志
     * @return R
     */
	@ApiOperationSupport(order = 20)
    @Operation(summary = "修改API日志", description = "修改API日志")
    @SysLog("修改API日志")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('bizs_ApiLog_edit')")
    public R updateById(@RequestBody ApiLog req) {
        return R.ok(apiLogService.updateById(req));
    }

    /**
     * 通过id删除API日志
     * @param ids id列表
     * @return R
     */
	@ApiOperationSupport(order = 30)
    @Operation(summary = "通过id删除API日志", description = "通过id删除API日志")
    @SysLog("通过id删除API日志")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('bizs_ApiLog_del')")
    public R remove(@RequestBody Long[] ids) {
        return R.ok(apiLogService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * 导出excel 表格
     * @param req 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
	@ApiOperationSupport(order = 40)
    @Operation(summary = "导出excel表格", description = "")
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('bizs_ApiLog_export')")
    public List<ApiLog> export(ApiLog req, Long[] ids) {
        return apiLogService.list(Wrappers.lambdaQuery(req).in(ArrayUtil.isNotEmpty(ids), ApiLog::getId, ids));
    }

	/**
     * 构建查询条件
     * @param req
     * @return
     */
    @NotNull
    private static LambdaQueryWrapper<ApiLog> buildQueryWrapper(ApiLog req) {
        LambdaQueryWrapper<ApiLog> wrapper = Wrappers.lambdaQuery(ApiLog.class);
		if(req.hasRangeTime()) {
           	wrapper.between(ApiLog::getCreateTime, req.getRangeTime()[0], req.getRangeTime()[1]);
        }
		wrapper.and(
                StrUtil.isNotBlank(req.getSearch()),
                w -> w.like(ApiLog::getId, req.getSearch())
                        .or().like(ApiLog::getUri, req.getSearch())
                        .or().like(ApiLog::getMethod, req.getSearch())
                        .or().like(ApiLog::getHeaders, req.getSearch())
                        .or().like(ApiLog::getQuery, req.getSearch())
                        .or().like(ApiLog::getBody, req.getSearch())
                        .or().like(ApiLog::getResponse, req.getSearch())
                        .or().like(ApiLog::getIp, req.getSearch())
                        .or().like(ApiLog::getBeginDate, req.getSearch())
                        .or().like(ApiLog::getEndDate, req.getSearch())
        );

        return wrapper;
    }

}
